package runjar;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Properties;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import openapi.dto.ApiCommonParamDto;
import openapi.util.SignUtil;

public class Md5RunMain {
	
	public static final String SIGN_METHOD_RSA = "RSA";
	public static final String SIGN_METHOD_MD5 = "MD5";

	public static void main(String[] args) throws Exception {
		String usrdir = System.getProperty("user.dir");
		String proppath = usrdir + "\\openapi.json";
		String confpath = usrdir + "\\conf.properties";
		Properties prop = new Properties();
		FileInputStream fis = new FileInputStream(confpath);
		try {
			prop.load(fis);
		} finally {
			fis.close();
		}
		File file = new File(proppath);
//		System.out.println(usrdir);
		StringBuilder sbb = new StringBuilder();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
			String line = null;
			while( (line=br.readLine())!=null ){
				sbb.append(line);
			}
			JSONObject jsonobj = JSON.parseObject(sbb.toString());
			ApiCommonParamDto dto = new ApiCommonParamDto();
			if(jsonobj.containsKey("REQUEST")){
				Map<String,Object> reqMap = (Map<String,Object>)jsonobj.get("REQUEST");
				Map<String,Object> hrtAttrMap = (Map<String,Object>)reqMap.get("HRT_ATTRS");
				Object reqData = reqMap.get("REQUEST_DATA");
				System.out.println("===");
				System.out.println(reqData);
				
				dto.setApiVersion(hrtAttrMap.get("Api_Version").toString());
				dto.setApiID(hrtAttrMap.get("Api_ID").toString());
				dto.setAppToken(hrtAttrMap.get("App_Token").toString());
				dto.setSysID(hrtAttrMap.get("Sys_ID").toString());
				dto.setAppSubId(hrtAttrMap.get("App_Sub_ID").toString());
				dto.setPartnerID(hrtAttrMap.get("Partner_ID").toString());
				dto.setAppPubID(hrtAttrMap.get("App_Pub_ID").toString());
				dto.setTimeStamp(hrtAttrMap.get("Time_Stamp").toString());
				
				dto.setSignMethod(SIGN_METHOD_MD5);
				
				dto.setFormat(hrtAttrMap.get("Format").toString());
				dto.setReqdate(reqData.toString());
				
				String appAppSecret = prop.getProperty("App_Secret");
				String sign = SignUtil.md5_sign(dto, appAppSecret);
				System.out.println("===sign===");
				System.out.println( sign );
				System.out.println("---");
				
				for(String key : hrtAttrMap.keySet()){
					System.out.println( String.format("%s: %s", key, hrtAttrMap.get(key)) );
				}
			}
			System.out.println("---");
			for(String key : jsonobj.keySet()){
				System.out.println( String.format("%s: %s", key, jsonobj.get(key)) );
			}
		} finally {
			br.close();
		}
	}

}
